package com.blb.gateway_service.filter;

import com.blb.common.entity.UserInfo;
import com.blb.common.utils.CookieUtils;
import com.blb.common.utils.JwtUtils;
import com.blb.gateway_service.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.misc.Request;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 登录鉴权的过滤器
 */
@Component
public class AuthFilter extends ZuulFilter {

    @Autowired
    private JwtProperties properties;

    @Override
    public String filterType() {
        //前置过滤器
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 99;
    }

    //是否进行过滤，true过滤（执行run方法），false（跳过run）
    @Override
    public boolean shouldFilter() {
        //读取当前请求的地址
        String uri = RequestContext.getCurrentContext().getRequest().getRequestURI();
        List<String> whiteList = properties.getWhiteList();
        //如果地址以白名单中的地址为开头，就不过滤
        for(String str : whiteList){
            if(uri.startsWith(str)){
                return false;
            }
        }
        //不是白名单就过滤
        return true;
    }

    //过滤逻辑
    @Override
    public Object run() throws ZuulException {
        //先从cookie中读取token
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String token = CookieUtils.getCookieValue(request, properties.getCookieName());
        //使用公钥对token进行解析
        try {
            UserInfo user = JwtUtils.getInfoFromToken(token, properties.getPublicKey());
            return user;
        }catch (Exception ex){
            ex.printStackTrace();
            //登录拦截
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(401);
        }
        return null;
    }
}
